package com.whzykj.job;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.whzykj.common.CommonUtils;
import com.whzykj.common.DateUtil;
import com.whzykj.common.DbUtil;
import com.whzykj.common.SystemRunParamCache;
import com.whzykj.model.OrderInfo;
import com.whzykj.model.RechargeBill;

public class OrderJob implements Job{
	public void execute(JobExecutionContext context)throws JobExecutionException {
		closeNoPayOrder();				// 执行截止下单后关闭订单的操作
		setTomorrowPriceAndStore();		// 自动设置价格和库存(如果有设置则不执行该操作)
		closePreRechargeBill();			// 自动关闭预充值
		List<Record> orderList = OrderInfo.me.getOrder();
		if(orderList != null && orderList.size()>0)
		{
			 for(Record rd:orderList)
			 {
				 Date orderdate = rd.getDate("order_date");
				 String order_date =CommonUtils.getDateStr(orderdate);
				 String now_date = DateUtil.getNow();
				 int goods_id=rd.getInt("goods_id");
				 int sale_num = rd.getInt("sale_num");
				 String order_id = rd.getStr("order_id");
				 try {
					 // true 未超过一小时，false 超过一小时
					 boolean flag= DateUtil.judgmentDate(order_date, now_date);
					 if(!flag)
					 {
						 String couponQry = " update store set sale_num=sale_num-? where goods_id = ? and date(set_date) = curdate() ";
						 int count = Db.update(couponQry,sale_num,goods_id);		
						 if(count >0)
						 {
						    OrderInfo order = OrderInfo.me.findById(order_id);
						    order.set("status", "over");
						    order.update();
						 }
					 }
				} catch (Exception e) {
					e.printStackTrace();
				}
			 }
		}
	}
	
	/**
	 * 截止下单后的规定时间内，自动关闭未付款的订单
	 */
	private void closeNoPayOrder(){
		String order_end_time=SystemRunParamCache.cache.getParamValue("order_end_time");		// 从缓存中获取订单截止时间（格式：19:30:00）
		String last_close_time=SystemRunParamCache.cache.getParamValue("last_close_time");		// 从缓存中获取订单截止后订单自动关闭时间（时间单位：分钟）
		String today_end_time_str=DateUtil.getToday()+" "+order_end_time;						// 获取当天订单截止时间字符串
		Date today_end_time=DateUtil.convertFullStringToDate(today_end_time_str);				// 获取当天订单截止日期对象
		long last_end_time=today_end_time.getTime()+1000*60*Integer.valueOf(last_close_time);	// 获取当天订单截止后自动关闭订单的时间点
		long current_time=new java.util.Date().getTime();										// 获取当前时间的毫秒数
		if(current_time>=last_end_time && current_time<last_end_time+1000*60){
			List<Record> orderList=Db.find("SELECT oi.ORDER_ID FROM orderinfo oi WHERE oi.STATUS='no_pay'");
			if(orderList!=null && orderList.size()>0){
				for(Record rec:orderList){
					int res=OrderInfo.me.closeOrder(rec.getStr("ORDER_ID"));
					if(res>0){
						// 此处将自动关闭订单的操作记录到日志中
						
					}
				}
			}	
		}
	}
	
	/**
	 * 自动关闭预充值的账单（从系统配置表中获取时间）
	 */
	public void closePreRechargeBill(){
		String recharge_close_time=SystemRunParamCache.cache.getParamValue("recharge_close_time");		// 从缓存中获取订单截止后订单自动关闭时间（时间单位：分钟）
		long close_time=(recharge_close_time==null?60:Long.valueOf(recharge_close_time));
		List<RechargeBill> bList=RechargeBill.dao.find("select sn,create_time from rechargebill where trade_status='00'");	// 查找预充值的流水
		List<String> sqlList=null;
		String sn=null;
		if(bList!=null && bList.size()>0){
			sqlList=new ArrayList<String>();
			for(RechargeBill rb:bList){
				Timestamp create_time=rb.getTimestamp("create_time");
				long create_times=create_time.getTime();
				long now_times=new java.util.Date().getTime();
				if(now_times-create_times>=close_time*60*1000){		// 如果间隔时间大于等于指定的预充值自动关闭时间
					sn=rb.getStr("sn");
					String sql="update rechargebill set trade_status='03' where sn='"+sn+"'";
					sqlList.add(sql);
				}
			}
		}
		try{
			boolean res=DbUtil.batch(sqlList);
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
	/**
	 * 系统自动判断需要设置明天的价格或库存
	 */
	private void setTomorrowPriceAndStore(){
		String today = DateUtil.getToday();
		String startTime = today + " 23:58:00"; 	// 自动执行起始时间
		String endTime = today + " 23:59:00"; 		// 自动执行截止时间
		SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			java.util.Date start = dfs.parse(startTime);
			java.util.Date end = dfs.parse(endTime);
			java.util.Date now = new java.util.Date();
			long s = start.getTime();
			long e = end.getTime();
			long n = now.getTime();
			if (n >= s && n < e) {
				// 获取第二天的日期字符串
				long time=new Date().getTime()+1000*60*60*24;
				Date tomorrow=new Date(time);
				String str=DateUtil.convertDateToString(tomorrow);
				String price_sql="select COUNT(1) from price where SET_DATE='"+str+"'";
				String store_sql="select COUNT(1) from store where SET_DATE='"+str+"'";
				int price_cnt=Db.queryLong(price_sql).intValue();
				int store_cnt=Db.queryLong(store_sql).intValue();
				List<String> sqlList=new ArrayList<String>();
				StringBuffer sql=null;
				if(price_cnt==0){
					sql=new StringBuffer("insert into price(SET_DATE,GOODS_ID,SALE_PRICE,UNIT_PRICE,MINUS_PRICE,UPDATE_USERID,UPDATE_TIME,STATION_ID) ");
					sql.append("select '"+str+"' as SET_DATE,GOODS_ID,SALE_PRICE,UNIT_PRICE,MINUS_PRICE,UPDATE_USERID,'"+DateUtil.getNow()+"' as UPDATE_TIME,STATION_ID from price WHERE SET_DATE='"+DateUtil.getToday()+"'");
					sql.append(" and GOODS_ID in (select GOODS_ID from goodsinfo where goods_status=1)");
					sqlList.add(sql.toString());
				}else{
					System.out.println("价格已经设置");
				}
				if(store_cnt==0){
					sql=new StringBuffer("insert into store(set_date,goods_id,store_num,sale_num,sale_price,limit_num,UPDATE_userid,UPDATE_time) ");
					sql.append("select '"+str+"' AS set_date,s.goods_id,s.store_num,0 as sale_num,s.sale_price,s.limit_num,106 as update_userid,'"+DateUtil.getNow()+"' as update_time ");
					sql.append("from store s where s.set_date='"+DateUtil.getToday()+"'");
					sql.append(" and GOODS_ID in (select GOODS_ID from goodsinfo where goods_status=1)");
					sqlList.add(sql.toString());
				}else{
					System.out.println("库存已经设置");
				}
				try{
					if(sqlList!=null && sqlList.size()>0){
//						int[] cnts=Db.batch(sqlList, 100);
						boolean res=DbUtil.batch(sqlList);
					}	
				}catch(Exception ex){
					ex.printStackTrace();
				}
			} 
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
